<template>

    <Head @selectDate="selectDate"></Head>
    <div class="recordWeight">
        <van-pull-refresh v-model="loading" @refresh="onRefresh">
            <div class="userInfo">
                <div class="username" v-if="userInfo">你好，{{ userInfo.nickname }}</div>
                <div class="encourage" v-if="weightList.length && targetList.length">今天也要加油哦！距离目标体重还差 {{
                    (weightList[0].nowWeight
                        - targetList[0].targetWeight).toFixed(1) }}kg
                </div>
                <div class="encourage" v-else>暂无数据</div>
                <div class="progressBar" @click="changeWeight">
                    <van-circle v-model:current-rate="currentRate" :rate="rate" :clockwise="false"
                        start-position="right" :color="gradientColor" size="3.2rem" :stroke-width="80">
                        <template #default>
                            <div class="rate">{{ rate.toFixed(0) }}%</div>
                            <span>完成度</span>
                            <div class="target" v-if="targetList.length">目标 {{ (+targetList[0].targetWeight).toFixed(1)
                                }}kg
                            </div>
                        </template>
                    </van-circle>
                </div>
            </div>
            <div class="userDetail">
                <ul>
                    <li class="weight" @click="changeWeight">
                        <div class="projectName">当前体重</div>
                        <div class="projectData" v-if="weightList.length">{{
                            (+weightList[0].nowWeight).toFixed(1)
                        }}kg</div>
                        <div class="projectData" v-else>暂无数据</div>
                        <div class="projectTarget" v-if="weightList.length === 7">较上周{{
                            (weightList[0].nowWeight -
                                weightList[6].nowWeight).toFixed(1) }}kg
                        </div>
                        <div class="projectTarget" v-else>暂无上周数据</div>
                    </li>
                    <li class="diet" @click="changeIntake">
                        <div class="projectName">今日摄入</div>
                        <div class="projectData">{{ foodList.reduce((pre, item) => {
                            return pre + item.calorie
                        }, 0) }}kcal</div>
                        <div class="projectTarget" v-if="targetList.length">目标 {{ targetList[0].targetIntake }}kcal
                        </div>
                    </li>
                    <li class="sport" @click="changeConsume">
                        <div class="projectName">今日消耗</div>
                        <div class="projectData">{{ todaySportList.reduce((pre, item) => {
                            return pre + item.calorie
                        }, 0) }}kcal</div>
                        <div class="projectTarget" v-if="targetList.length">目标 {{ targetList[0].targetConsume }}kcal
                        </div>
                    </li>
                </ul>
            </div>
            <div class="echarts" ref="echartsRef"></div>
            <div class="recordDiet">
                <div class="title">
                    <div class="name">今日饮食记录</div>
                    <div class="more" @click="goTab('/recordDiet')">查看更多</div>
                </div>
                <ul class="dataList">
                    <li v-for="item in foodList">
                        <i class="iconfont" :class="mealicons[item.mealType]"></i>
                        <div class="meal">
                            <p>{{ item.mealType }} - {{ item.mealName }}</p>
                            <span>{{ item.time }}</span>
                        </div>
                        <div class="calorie">{{ item.calorie }}kcal</div>
                    </li>
                </ul>
            </div>
            <div class="recordSport">
                <div class="title">
                    <div class="name">今日运动记录</div>
                    <div class="more" @click="goTab('/recordSport')">查看更多</div>
                </div>
                <ul class="dataList">
                    <li v-for="item in todaySportList">
                        <i class="iconfont" :class="sporticons[item.sportType]"></i>
                        <div class="sport">
                            <p>{{ item.sportType }}</p>
                            <span>{{ item.minute }}分钟</span>
                        </div>
                        <div class="calorie">{{ item.calorie }}kcal</div>
                    </li>
                </ul>
            </div>
        </van-pull-refresh>
    </div>
    <PopWeight @selectWeight="selectWeight" ref="PopWeightRef"></PopWeight>
    <PopIntake @selectIntake="selectIntake" ref="PopIntakeRef"></PopIntake>
    <PopConsume @selectConsume="selectConsume" ref="PopConsumeRef"></PopConsume>

</template>

<script setup>
import Head from '@/components/Head.vue'
import { ref, onMounted } from 'vue';
import PopWeight from '@/components/PopWeight.vue'
import { changeTargetWeight, changeNowWeight, getWeightData, getTargetData, getDietData, changeTargetIntake, changeTargetConsume, getSportData } from '@/api/index.js'
import { showSuccessToast, showFailToast } from 'vant';
import * as echarts from 'echarts/core';
import { GridComponent } from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import { formateDate } from '@/utils/formateDate.js'
import { mealicons, sporticons } from '@/utils/icons.js'
import PopIntake from '@/components/popIntake.vue'
import PopConsume from '@/components/PopConsume.vue'
import { useRouter } from 'vue-router';


echarts.use([GridComponent, LineChart, CanvasRenderer, UniversalTransition]);


const router = useRouter()
const time = ref((new Date(new Date().setHours(8, 0, 0, 0)).getTime()).toString())
const gradientColor = {
    '0%': '#00008B',
    '100%': '#ADD8E6',
};
const currentRate = ref(0);
const rate = ref(0)
const userInfo = ref(JSON.parse(localStorage.getItem('userInfo')));
// console.log(userInfo);
const PopWeightRef = ref('')
const targetWeight = ref('0')
const nowWeight = ref('0')
const weightList = ref([])
const echartsRef = ref('')
const targetList = ref([])
const foodList = ref([])
const PopIntakeRef = ref('')
const targetIntake = ref('0')
const PopConsumeRef = ref('')
const targetConsume = ref('0')
const loading = ref(false);
const sportList = ref([])
const todaySportList = ref([])



// 查看更多
const goTab = (path) => {
    router.push(`${path}`)
}

// 获取最近七天的体重数据
const getSevenData = async () => {
    const res = await getWeightData(time.value)
    weightList.value = res.data
    // console.log(weightList.value);
    if (weightList.value.length && targetList.value.length) {
        rate.value = (targetList.value[0].targetWeight / weightList.value[0].nowWeight) * 100
    } else {
        rate.value = 0
    }
    loadChart(weightList.value)
}

// 获取用户的目标体重、目标摄入和目标消耗
const getUserData = async () => {
    const res = await getTargetData()
    targetList.value = res.data
    // console.log(targetList.value);
}

onMounted(async () => {
    await getUserData()
    await getSevenData()
    await getDayData()
    await getLastWeekData()
})

// 下拉刷新
const onRefresh = async () => {
    await getUserData()
    await getSevenData()
    await getDayData()
    await getLastWeekData()
    showSuccessToast('刷新成功');
    loading.value = false;
};

// 选择日期
const selectDate = async (type) => {
    time.value = (new Date(type.join('-')).getTime()).toString()
    await getSevenData()
    await getDayData()
    await getLastWeekData()
    showSuccessToast('切换成功')
}

// 是否显示修改体重组件
const changeWeight = () => {
    PopWeightRef.value.show = true
}

// 是否显示修改目标摄入组件
const changeIntake = () => {
    PopIntakeRef.value.show = true
}

// 是否显示修改目标消耗组件
const changeConsume = () => {
    PopConsumeRef.value.show = true
}

// 修改目标体重和当前体重
const selectWeight = async (weight) => {
    // console.log(weight);
    targetWeight.value = weight.targetWeight
    nowWeight.value = weight.nowWeight
    const res = await changeTargetWeight({ targetWeight: Number(targetWeight.value) })
    const res2 = await changeNowWeight({ nowWeight: Number(nowWeight.value), time: time.value })
    if (res.flag) {
        showSuccessToast(res.msg)
        await getUserData()
        await getSevenData()
    } else {
        showFailToast(res.msg)
    }
}

// 修改目标摄入热量
const selectIntake = async (intake) => {
    targetIntake.value = intake.targetIntake
    // console.log(targetIntake.value);
    const res = await changeTargetIntake({ targetIntake: Number(targetIntake.value) })
    if (res.flag) {
        showSuccessToast(res.msg)
        await getUserData()
    } else {
        showFailToast(res.msg)
    }
}

// 修改目标消耗热量
const selectConsume = async (consume) => {
    targetConsume.value = consume.targetConsume
    // console.log(targetConsume.value);
    const res = await changeTargetConsume({ targetConsume: Number(targetConsume.value) })
    if (res.flag) {
        showSuccessToast(res.msg)
        await getUserData()
    } else {
        showFailToast(res.msg)
    }
}

// 获取一天的餐食
const getDayData = async () => {
    const res = await getDietData(time.value)
    foodList.value = res.data
    // console.log(foodList.value);
}

// 请求本周的运动数据
const getLastWeekData = async () => {
    const res = await getSportData(time.value)
    sportList.value = res.data
    todaySportList.value = sportList.value.filter(item => {
        return item.create_time === time.value
    })
    // console.log(sportList.value);
}

// echarts
const loadChart = (weightList) => {
    const myChart = echarts.init(echartsRef.value);
    const typeData = []
    const weightData = []
    weightList.forEach(item => {
        typeData.unshift(formateDate(Number(item.create_time)).slice(1).join('/'))
        weightData.unshift(item.nowWeight)
    })

    const option = {
        xAxis: {
            type: 'category',
            data: typeData,
            axisTick: {
                alignWithLabel: true,
            },
            axisLabel: {
                fontSize: 11
            }
        },
        yAxis: {
            type: 'value',
            min: weightData[weightData.length - 1] - 10,
            max: weightData[0] + 10,
        },
        series: [
            {
                data: weightData,
                type: 'line'
            }
        ]
    };

    option && myChart.setOption(option);
}
</script>

<style lang="less" scoped>
.recordWeight {
    box-sizing: border-box;
    padding: 0 .3733rem;
    width: 100%;
    height: calc(100vh - 2.5347rem);
    background: #F9FAFB;
    overflow: scroll;

    .userInfo {
        .username {
            font-weight: 500;
            font-size: 0.48rem;
            color: #000000;
            line-height: 0.67rem;
            margin-top: 2px;
        }

        .encourage {
            font-weight: 400;
            font-size: 0.37rem;
            color: #4B5563;
            line-height: 0.56rem;
            margin-top: 0.19rem;
        }

        .progressBar {
            display: flex;
            justify-content: center;
            margin-top: 0.56rem;

            .rate {
                font-weight: 500;
                font-size: 0.56rem;
                color: #000000;
                line-height: 0.75rem;
                margin-top: .7467rem;
            }

            span {
                font-weight: 400;
                font-size: 0.32rem;
                color: #6B7280;
                line-height: 0.48rem;
            }

            .target {
                font-weight: 400;
                font-size: 0.29rem;
                color: #9CA3AF;
                line-height: 0.37rem;
            }
        }
    }

    .userDetail {
        margin-top: .56rem;

        ul {
            display: flex;

            li {
                flex: 1;
                padding: .4267rem;
                background-color: #fff;
                box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.05);
                border-radius: 12px 12px 12px 12px;

                &.diet {
                    margin: 0 .2667rem;
                }

                .projectName {
                    font-weight: 400;
                    font-size: 0.32rem;
                    color: #6B7280;
                    line-height: 0.48rem;
                    margin-bottom: .08rem;
                }

                .projectData {
                    font-weight: 500;
                    font-size: 0.48rem;
                    color: #000000;
                    line-height: 0.67rem;
                    margin-bottom: .08rem;
                }

                .projectTarget {
                    font-weight: 400;
                    font-size: 0.29rem;
                    color: #6B7280;
                    line-height: 0.37rem;
                }

                &.weight {
                    .projectTarget {
                        color: #22C55E;
                    }
                }
            }
        }
    }

    .echarts {
        width: 100%;
        height: 5.33rem;
        background-color: #fff;
        margin-top: .56rem;
        border-radius: 0.19rem;
    }

    .recordDiet,
    .recordSport {
        margin-top: 0.56rem;
        padding: .3733rem;
        background-color: #fff;
        margin-bottom: .56rem;
        border-radius: 0.19rem;

        .title {
            display: flex;
            justify-content: space-between;

            .name {
                font-weight: 500;
                font-size: 0.37rem;
                color: #000000;
                line-height: 0.56rem;
            }

            .more {
                font-weight: 400;
                font-size: 0.32rem;
                color: #000000;
                line-height: 0.48rem;
            }
        }

        .dataList {
            li {
                display: flex;
                align-items: center;
                margin-top: 0.37rem;

                .iconfont {
                    flex: 1;
                    color: #3176FF;
                    text-align: center;
                    font-size: .8rem;
                }

                .meal,
                .sport {
                    flex: 3;

                    p {
                        font-weight: 500;
                        font-size: 0.37rem;
                        color: #000000;
                        line-height: 0.56rem;
                    }

                    span {
                        font-weight: 400;
                        font-size: 0.32rem;
                        color: #6B7280;
                        line-height: 0.48rem;
                    }
                }

                .calorie {
                    flex: 1;
                    text-align: right;
                    font-weight: 400;
                    font-size: 0.37rem;
                    color: #6B7280;
                    line-height: 0.56rem;
                }
            }
        }
    }


}
</style>